# # 
#  util.py
#  ExpectIT
#  
#  Author: Marvin S. Addison
#  Date: 2007-10-15
#  Version: $Revision: $
#  Updated: $Date: $
#  Copyright 2008 Marvin S. Addison. All rights reserved.
#  See LICENSE.txt for licensing information.
#

import sys
import re

"""Regular expression to match built-in functions and variables."""
__BUILTIN_RE = re.compile('__\w+__')

def load_object(obj, dict, exclude_keys=[]):
	"""Sets the properties of the given object using the supplied dictionary.
	Dictionary key names are used for property names.
	If the exclude_keys argument is provided, any keys appearing in that
	list are excluded from loading."""
	for k in dict.keys():
		if exclude_keys.count(k) == 0:
			setattr(obj, k, dict[k])

def clone(a, b):
	"""Performs a shallow clone by copying all properties from a to b.
	Of course a and b must be of the same type."""
	for attr in dir(a):
		if not callable(attr) and not __BUILTIN_RE.search(attr):
			setattr(b, attr, getattr(a, attr))

def printerr(s):
	"""Prints a line of text to standard error."""
	sys.stderr.write('%s\n' % s)

def quit(msg):
	"""Exits the current process gracefully with a status message."""
	print msg
	print 'Quitting.'
	sys.exit(1)

def read_file(path):
	"""Reads the contents of the file at the specified path and 
	returns contents as a string."""
	f = open(path, 'r')
	contents = ''
	try:
		return f.read()
	finally:
		f.close()

def write_file(path, s):
	"""Writes the given string to the specified file."""
	f = open(path, 'w')
	try:
		f.write(s)
	finally:
		f.close()
